/**
 * 
 */
package co.edu.udem.dao.impl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import co.edu.udem.dao.LoginDao;
import co.edu.udem.domain.User;
import co.edu.udem.service.ServiceResponse;
import co.edu.udem.service.login.SessionManager;


/**
 * @since 18/07/2012
 */
@Repository("loginDao")
@Transactional
public class LoginDaoImpl implements LoginDao {

  @Resource(name = "sessionFactory")
  private SessionFactory sessionFactory;

  /** Instance of session. */
  @Autowired
  private SessionManager sessionManager;

  /*
   * (non-Javadoc)
   * 
   * @see co.edu.udem.dao.LoginDao#createSession(java.lang.String, java.lang.String, int)
   */
  public User createSession(String userCode, String password, int userType) {
    ServiceResponse response = new ServiceResponse();
    Session session = sessionFactory.getCurrentSession();
    Query query = session
        .createQuery("FROM  User Where userCode = :userCode And password = :password And userType = :userType");
    query.setParameter("userCode", userCode);
    query.setParameter("password", password);
    query.setParameter("userType", userType);
    User user = (User) query.uniqueResult();
    if (user == null) {
      return null;
    }
    String key = user.getUserCode() + "|" + user.getPassword() + "|" + user.getUserType();
    user.setSessionId(sessionManager.insertOrUpdateUserSession(key));
    return user;
  }

  public User validateSession(String userCode, String password, int userType) {
    return createSession(userCode, password, userType);
  }

}
